<template>
  <div class="CarTrace" v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(255, 255, 255, 0.6)">
    <div class="main">
      <div ref="qqmap" class="map" id="qqmap"></div>
      <el-card class="box-card">
        <el-button round class="btn" @click="palyAni">播放动画</el-button>
        <el-button round class="btn" @click="pauseAni">暂停动画</el-button>
        <el-button round class="btn" @click="restartAni">重新播放</el-button>
      </el-card>
    </div>
    <div class="right">
      <h2 class="title">途径路线</h2>
      <el-timeline>
        <el-timeline-item v-for="(item, index) in mapPoints" :key="index" :timestamp="item.time">{{ item.des
          }}</el-timeline-item>
      </el-timeline>
    </div>
  </div>
</template>

<script>
// import { carPosition } from "@/api/public";
// import { deepClone } from "@/utils/tool.js";
import { getHeader } from '@/utils/tool'
import axios from 'axios'
export default {
  name: "CarTrace",
  props: ['id'],
  data() {
    return {
      mapPoints: [],
      traceMap: null,
      traceMarker: null,
      loading: false,
    };
  },
  mounted() {
    //接口等待时间过长 暂时用模拟数据
    // carPosition({
    //   id: 228757
    // }).then(res => {
    //   if (res.code == 200) {
    //     this.mapPoints = res.arr;
    //     this.initMap();
    //   }
    // });
    this.getPoints();
  },
  methods: {
    async getPoints() {
      this.loading = true;
      axios({
        url: `https://api.zhgylgl.com/api/shipper/carPosition?id=${this.id}`,
        methods: 'get',
        headers: getHeader()
      }).then(res => {
        this.loading = false;
        if (res.data.code == 200 && res.data.data.length > 1) {
          this.mapPoints = res.data.data;
          this.initMap();
        } else if (res.data.code == 316) {
          this.$message.error(res.data.msg)
        } else if (!res.data || !res.data.data.length > 1) {
          this.$message.error('暂无数据')
        }
      })
    },
    initMap() {
      let center = new TMap.LatLng(39.984104, 116.307503); //设置中心点坐标
      //初始化地图
      this.traceMap = new TMap.Map(this.$refs.qqmap, {
        center: center,
        mapStyleId: "style1",
        // minZoom: 1, //此处设置地图的缩放级别  最小值是6
        // maxZoom: 20, //此处设置地图的缩放级别  最大值是7
        zoom: 15
      });
      var endCar = this.mapPoints[0];
      var start = this.mapPoints[this.mapPoints.length - 1];
      //计算距离
      var startPoint = new TMap.LatLng(start.lat, start.lon);
      var endPoint = new TMap.LatLng(endCar.lat, endCar.lon);
      // 计算路径的实际距离 用于优化速度 单位为米
      var distance = TMap.geometry.computeDistance([startPoint, endPoint]);

      //小车移动路线
      var path = this.mapPoints.reverse().map(item => {
        return new TMap.LatLng(item.lat, item.lon);
      });

      //创建LatLngBounds实例
      var latlngBounds = new TMap.LatLngBounds();
      //将坐标逐一做为参数传入extend方法，latlngBounds会根据传入坐标自动扩展生成
      //将起始点向左偏移一下
      // let boundsPath = [new TMap.LatLng(start.lat, start.lon), endPoint];
      for (var i = 0; i < path.length; i++) {
        latlngBounds.extend(path[i]);
      }
      //调用fitBounds自动调整地图显示范围
      this.traceMap.fitBounds(latlngBounds);

      var polylineLayer = new TMap.MultiPolyline({
        map: this.traceMap, // 绘制到目标地图
        // 折线样式定义
        styles: {
          style_blue: new TMap.PolylineStyle({
            color: "#3777FF", // 线填充色
            width: 2, // 折线宽度
            borderWidth: 2, // 边线宽度
            borderColor: "#FFF", // 边线颜色
            lineCap: "round", // 线端头方式
            eraseColor: "rgba(190,188,188,1)"
          })
        },
        geometries: [
          {
            id: "erasePath",
            styleId: "style_blue",
            paths: path
          }
        ]
      });
      //创建mareker（小车）
      this.traceMarker = new TMap.MultiMarker({
        map: this.traceMap,
        styles: {
          "car-down": new TMap.MarkerStyle({
            width: 40,
            height: 40,
            anchor: {
              x: 20,
              y: 20
            },
            faceTo: "map",
            rotate: 180,
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/car.png"
          }),
          start: new TMap.MarkerStyle({
            width: 25,
            height: 35,
            anchor: { x: 16, y: 32 },
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/start.png"
          }),
          end: new TMap.MarkerStyle({
            width: 25,
            height: 35,
            anchor: { x: 16, y: 32 },
            src: "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/end.png"
          })
        },
        geometries: [
          {
            id: "car",
            styleId: "car-down",
            position: new TMap.LatLng(start.lat, start.lon)
          },
          {
            id: "start",
            styleId: "start",
            position: new TMap.LatLng(start.lat, start.lon)
          },
          {
            id: "end",
            styleId: "end",
            position: new TMap.LatLng(endCar.lat, endCar.lon)
          }
        ]
      });

      this.traceMarker.on("moving", e => {
        var passedLatLngs = e.car && e.car.passedLatLngs;
        if (passedLatLngs) {
          // 使用路线擦除接口 eraseTo, https://lbs.qq.com/webApi/javascriptGL/glDoc/glDocVector
          polylineLayer.eraseTo(
            "erasePath",
            passedLatLngs.length - 1,
            passedLatLngs[passedLatLngs.length - 1]
          );
        }
      });

      var speed = 1000; //speed为指定速度，正整数，单位：千米/小时
      //计划30秒走完 用当前距离distance除以 30 然后 * 3600 得出speed值
      speed = (distance / 1000 / 30) * 3600;

      //调用moveAlong，实现小车移动
      this.traceMarker.moveAlong(
        {
          car: {
            //设置让"car"沿"path"移动，速度70公里/小时
            path,
            speed: speed
          }
        },
        {
          autoRotation: true //车头始终向前（沿路线自动旋转）
        }
      );

      //设置延迟 为当前显示的轨迹范围加个边距
      setTimeout(() => {
        let currentZoom = this.traceMap.getZoom();
        this.traceMap.setZoom(currentZoom - 0.4);
      }, 500);
    },
    palyAni() {
      this.traceMarker.resumeMove();
    },
    pauseAni() {
      this.traceMarker.pauseMove();
    },
    restartAni() {
      this.traceMarker.stopMove(); //先暂定轨迹动画然后再销毁 否则报错
      this.traceMap && this.traceMap.destroy();
      this.initMap();
    }
  }
};
</script>

<style lang="scss">
.CarTrace {
  width: 100%;
  height: 100%;
  overflow: hidden;
  display: flex;
}

.CarTrace .main {
  width: 80%;
  height: 100%;
  position: relative;
}

.CarTrace .main .box-card {
  position: absolute;
  z-index: 9999999;
  right: 10px;
  bottom: 10px;
  display: flex;
}

.CarTrace .main .map {
  width: 100%;
  height: 100%;
}

.CarTrace .right {
  padding: 0 10px;
  flex: 1;
  margin-left: 10px;
  overflow: auto;
}

.CarTrace .right .title {
  text-align: left;
  margin-bottom: 10px;
}

/*# sourceMappingURL=css.css.map */
</style>
